package com.example.demo.handler;

import dev.langchain4j.data.message.ChatMessageType;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(ChatMessageType.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ChatMessageTypeHandler extends BaseTypeHandler<ChatMessageType> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, ChatMessageType parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.name());  // 存储枚举的 name() 值，如 "USER"
    }

    @Override
    public ChatMessageType getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return value == null ? null : ChatMessageType.valueOf(value);  // 解析 name() 还原枚举
    }

    @Override
    public ChatMessageType getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return value == null ? null : ChatMessageType.valueOf(value);
    }

    @Override
    public ChatMessageType getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return value == null ? null : ChatMessageType.valueOf(value);
    }
}

